package com.uniview.web.contorller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.uniview.base.BaseController;
import com.uniview.entity.po.Employees;
import com.uniview.entity.po.ExportLog;
import com.uniview.entity.po.RegionManager;
import com.uniview.entity.vo.OrderDetailReport;
import com.uniview.entity.vo.Pager;
import com.uniview.entity.vo.ResultMessage;
import com.uniview.entity.vo.TableJsonVO;
import com.uniview.service.ExportLogService;
import com.uniview.service.RegionManagerService;
import com.uniview.service.report.OrderDetailReportService;

@Controller
@RequestMapping(value = "/report")
public class OrderDetailReportController extends BaseController {
	Logger logger = Logger.getLogger(OrderDetailReportController.class);

	@Autowired
	private OrderDetailReportService orderDetailReoprtService;

	@Autowired
	private RegionManagerService regionManagerService; // 片区管理接口

	@Autowired
	private ExportLogService exportLogService; // 导出日志记录

	@Value("#{configProperties['uniview.deptLevel']}")
	private Integer officeLevel;

	@RequestMapping(value = "/findOrderDetailReoprt")
	@ResponseBody
	public TableJsonVO findOrderDetailReoprt(HttpServletRequest request) {
		try {
			int page = ServletRequestUtils.getIntParameter(request, "page", 0);
			int limit = ServletRequestUtils.getIntParameter(request, "limit", 20);
			String handler = ServletRequestUtils.getStringParameter(request, "handler");
			Employees employees = (Employees) request.getSession().getAttribute("employees");
			RegionManager rm = this.regionManagerService.findRegionManagerByWorkNo(employees.getEmpCode());
			String area = employees.feachOffice(officeLevel);
			if (rm != null) {
				area = rm.getRegionName();
			}
			// area=area==null?employees.getOrgName():area;
			String startTime = ServletRequestUtils.getStringParameter(request, "startDate");
			String endTime = ServletRequestUtils.getStringParameter(request, "endDate");
			Pager<OrderDetailReport> pager = orderDetailReoprtService.findOrderDetailReoprt(handler, area, startTime,
					endTime, page, limit);
			if (pager != null && pager.getPagerList() != null && pager.getPagerList().size() > 0) {
				// return getTableJsonString(JsonMapper.toJsonString(pager.getPagerList()),
				// pager.getTotalRow());
				return getTableJsonVO(pager.getPagerList(), pager.getTotalRow());
			}
		} catch (Exception e) {
			logger.error("统计工单数据异常", e);
		}
		// return getTableJsonString("[]", 0);
		return getTableJsonVO(new ArrayList<OrderDetailReport>(), 0);
	}

	@SuppressWarnings("resource")
	@RequestMapping(value = "/ExportExcelByOrderDetail")
	@ResponseBody
	public ResultMessage ExportExcelByOrderDetail(HttpServletRequest request) {
		// 工时汇总
		try {
			String handler = ServletRequestUtils.getStringParameter(request, "handler");
			Employees employees = (Employees) request.getSession().getAttribute("employees");
			RegionManager rm = this.regionManagerService.findRegionManagerByWorkNo(employees.getEmpCode());
			String area = employees.feachOffice(officeLevel);
			if (rm != null) {
				area = rm.getRegionName();
			}
			// area=area==null?employees.getOrgName():area;
			String startTime = ServletRequestUtils.getStringParameter(request, "startDate");
			String endTime = ServletRequestUtils.getStringParameter(request, "endDate");
			List<OrderDetailReport> tempList = orderDetailReoprtService.findOrderDetailReoprt(handler, area, startTime,
					endTime);
			SXSSFWorkbook workbook = new SXSSFWorkbook();
			OutputStream out = null;
			String fileName = "部门工单统计表.xlsx";
			
			// 记录日志
			try {
				ExportLog log = new ExportLog.Builder().name(employees.getEmpName()).username(employees.getEmpCode())
						.log("部门工单统计导出-数量" + tempList.size()).opsDateTtime(new Date()).build();
				exportLogService.saveExportLog(log);
			} catch (Exception e) {
				logger.error("日志记录失败", e);
			}
			
			if (!tempList.isEmpty()) {
				try {
					String path = request.getSession().getServletContext().getRealPath("");
					path = path + "static/export/";
					File file = new File(path);
					if (!file.exists()) {
						file.mkdirs();
					}
					out = new FileOutputStream(path + fileName);
					logger.info("=========================" + path + fileName);
				} catch (FileNotFoundException e) {
					logger.error("导出目录不存在", e);
					try {
						workbook.close();
					} catch (IOException e1) {
						logger.error("excel工作区间关闭异常", e);
					}
					return getResult("导出目录不存在", false);
				}

				if (null != out) {
					writeExcelSheet(tempList, workbook, "工单明细统计");
					try {
						workbook.write(out);
						String url = request.getContextPath() + "/static/export/" + fileName;
						return this.getResult("导出成功", true, url);
					} catch (IOException e) {
						logger.error("excel导出异常", e);
					}
				}
			} else {
				return getResult("请先查询需要导出的数据！", false);
			}

		} catch (Exception e) {
			logger.error("导出异常", e);
		}

		return getResult("导出失败", false);
	}

	private static void writeExcelSheet(List<OrderDetailReport> wrlist, SXSSFWorkbook workbook, String title) {
		// 生成表格
		SXSSFSheet sheet = workbook.createSheet(title);
		// 设置表格默认列宽度为15个字节
		sheet.setDefaultColumnWidth((short) 25);
		// 生成一个样式
		CellStyle headerStyle = workbook.createCellStyle();
		// 设置这些样式
		headerStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
		setCellSytle(headerStyle);
		// 生成一个字体
		Font headerFont = workbook.createFont();
		headerFont.setColor(HSSFColor.BLACK.index);
		headerFont.setFontHeightInPoints((short) 12);
		headerFont.setBold(true);
		// 把字体应用到当前的样式
		headerStyle.setFont(headerFont);

		// 产生表格标题行
		String[] headers = { "工单编号", "工单类型", "工单提出人", "工单处理人", "所在办事处", "客户名称", "工单生成时间", "工单处理时间", "工单结束时间", "工单总工时",
				"客户满意度" };
		SXSSFRow row = sheet.createRow(0);
		// 创建表头
		for (int ii = 0; ii < headers.length; ii++) {
			SXSSFCell cell = row.createCell(ii);
			cell.setCellStyle(headerStyle);
			XSSFRichTextString text = new XSSFRichTextString(headers[ii]);
			cell.setCellValue(text);
		}

		CellStyle contentStyle = workbook.createCellStyle();
		contentStyle.setFillForegroundColor(HSSFColor.WHITE.index);
		setCellSytle(contentStyle);
		contentStyle.setWrapText(true);
		// 生成一个字体
		Font contentFont = workbook.createFont();
		contentFont.setColor(HSSFColor.BLACK.index);
		contentFont.setFontHeightInPoints((short) 12);
		contentFont.setBold(false);
		// 把字体应用到当前的样式
		contentStyle.setFont(contentFont);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		int index = 0;

		for (int k = 0; k < wrlist.size(); k++) {
			OrderDetailReport wr = wrlist.get(k);
			if (wr != null) {
				row = sheet.createRow(index + 1);
				SXSSFCell cell = row.createCell(0);
				cell.setCellStyle(contentStyle);
				cell.setCellValue(wr.getOrderNo());

				cell = row.createCell(1);
				cell.setCellStyle(contentStyle);
				cell.setCellValue(wr.getOrderFrom());

				cell = row.createCell(2);
				cell.setCellStyle(contentStyle);
				cell.setCellValue(wr.getCreator());

				cell = row.createCell(3);
				cell.setCellStyle(contentStyle);
				cell.setCellValue(wr.getHandle());

				cell = row.createCell(4);
				cell.setCellStyle(contentStyle);
				cell.setCellValue(wr.getArea());

				cell = row.createCell(5);
				cell.setCellStyle(contentStyle);
				cell.setCellValue(wr.getCustomerName());

				cell = row.createCell(6);
				cell.setCellStyle(contentStyle);
				cell.setCellValue(sdf.format(wr.getCreateTime()));

				cell = row.createCell(7);
				cell.setCellStyle(contentStyle);
				Date startTime = wr.getStartTime();
				cell.setCellValue(null != startTime ? sdf.format(wr.getStartTime()) : "");

				cell = row.createCell(8);
				cell.setCellStyle(contentStyle);
				Date endTime = wr.getEndTime();
				cell.setCellValue(null != endTime ? sdf.format(wr.getEndTime()) : "");

				cell = row.createCell(9);
				cell.setCellStyle(contentStyle);
				cell.setCellValue(wr.getOrderHours());

				cell = row.createCell(10);
				cell.setCellStyle(contentStyle);

				if (wr.getSatisfaction() == 0) {
					cell.setCellValue("不满意");
				}

				if (wr.getSatisfaction() == 1) {
					cell.setCellValue("满意");
				}

				if (wr.getSatisfaction() == 2) {
					cell.setCellValue("未回复");
				}

				index++;
			}
		}
	}

	public static void setCellSytle(CellStyle style) {
		style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
		style.setBorderBottom(BorderStyle.THIN);
		style.setBorderLeft(BorderStyle.THIN);
		style.setBorderRight(BorderStyle.THIN);
		style.setBorderTop(BorderStyle.THIN);
		style.setAlignment(HorizontalAlignment.CENTER);
		style.setVerticalAlignment(VerticalAlignment.CENTER);
	}
}
